import { ref } from "vue";
import { defineStore } from "pinia";
import UniStorage from "@/utils/UniStorage";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { AuthApi } from "@/api/auth";
import config from "@/config";
import { UserInfo } from "@/api/auth/model";
import { getWeixinCode } from "@/utils/uniUtils";
import { MyApi } from "@/api/my";
// app模块
export const useUserStore = defineStore("user", () => {
  const token = ref(getToken());
  // const token = ref('eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpZCI6MzksImlzcyI6IiIsImF1ZCI6IiIsImlhdCI6MTc0MjM5MTU1MSwiZXhwIjoxNzczOTI3NTUxfQ.XKFqYYZi1TNhai-4SEhb2KihNQdUG_ZyEXMyPqFx_4HcY7mFAujFhWqXFEHbTl1cgd_jYm4Ryq-snplFJgT9FRpS_QDm4afyPVmsJ5RrRROY3tusGjepQl_Tiqxi6s3V-P03SDce3NUpVkgIZAKFrqtKgFK5GtDVLICOzWWYnCU');
  const userInfo = ref<UserInfo | null>(
    UniStorage.get(config["USER_KEY"]) || null
  );

  // 用户登陆
  async function login(code: string) {
    return new Promise(async (resolve, reject) => {
      try {
        const wxCode = await getWeixinCode();
        const res = await AuthApi.wxLogin({
          code: wxCode,
          js_code: code,
        });

        if (res.success) {
          const { token: tokenVal, user } = res.data.data;
          token.value = tokenVal;
          console.log("token", token.value);
          userInfo.value = user;
          getUserInfo();
          setToken(tokenVal);
          UniStorage.set(config["USER_KEY"], user);
          resolve(res.data);
        }

        console.log("res", res);
      } catch (err) {
        uni.showToast({
          title: "登录失败",
          icon: "none",
        });
        console.log("err", err);
        reject(err);
      }
    });
  }

  // 获取用户信息
  async function getUserInfo() {
    return new Promise(async (resolve, reject) => {
      try {
        const res = await MyApi.getUserInfo();

        const { success, data } = res;
        if (success) {
          userInfo.value = data;
          resolve(data);
        }

        console.log("userInfo-request", res);
      } catch (err) {
        uni.showToast({
          title: "获取用户信息失败",
          icon: "none",
        });
        logout();
        reject(err);
      }
    });
  }

  // 用户退出登陆
  async function logout() {
    token.value = "";
    userInfo.value = null;
    UniStorage.remove(config["USER_KEY"]);
    removeToken();
  }

  return {
    token,
    userInfo,
    login,
    getUserInfo,
    logout,
  };
});
